<?php
/** Copyright 2014 TinPhp Systems, Inc.
 * @author zhangxilian 2014-1-20
 * @package TinPhp
 */
/** TinPHP框架配置文件加载类,由TinAppController
 *  */
class TinAppConf {
	private $conf;
	private static $_instance;
	
	public function __construct($filename) {
		$this->conf = self::load($filename);
	}
	
	/** 阻止用户复制对象实例 */
	public function __clone(){
		trigger_error('Clone is not allow',E_USER_ERROR);
	}
	
	/** 单例获取对象方法
     * @param string $filename 配置文件路径 */
	public static function getInstance($filename){
		if(!isset(self::$_instance)){
			$c = __CLASS__;
			self::$_instance = new $c($filename);
		}
		return self::$_instance;
	}
    /** 添加其他配置文件
     * @param string $filename 配置文件路径 */
	public function add($filename) {
		$newConf = self::load($filename);
		if ($newConf == null)
			$newConf = array ();
		foreach ($newConf as $newSecName => $newSecArr) {
			if ($this->conf[$newSecName]) { // have same section between old & new conf
				// replace old item/value pair
				foreach ($newSecArr as $newItemName => $newItemValue) {
					$this->conf[$newSecName][$newItemName] = $newItemValue;
				}
			} else {
				$this->conf[$newSecName] = $newSecArr;
			}
		}
	}
    /** 获取对象 */
	public function getConf() {
		return $this->conf;
	}
	/** 获取指定节点的指定值
     * @param string $sectionName 指定节点名称
     * @param string $itemName 指定Key名称
     * @return string
     *  */
	public function confValue($sectionName, $itemName) {
		return $this->conf[$sectionName][$itemName];
	}
    /** 获取指定节点的所有值，返回数组
     * @param string $sectionName 指定节点名称
     * @return array
     *  */
	public function confGroup($sectionName) {
		return $this->conf[$sectionName];
	}

	/**
	 * 加载INI配置文件
	 * @return: 2-dimension array
	 *          or empty array if file is not exists.
	 */
	private static function load($filename) {
		if (!file_exists($filename)) {
			return array ();
		}
		$iniSetting = array ();
		$lineArr = file($filename);
		foreach ($lineArr as $line) {
			$dataLine = trim($line);
			$firstChar = substr($dataLine, 0, 1);
			if ($firstChar != ';' && $dataLine != '') {
				if ($firstChar == '[' && substr($dataLine, -1, 1) == ']') {
					$sectionName = preg_replace('/[\[\]]/', '', $dataLine);
				} else {
					if (!isset ($sectionName)) {
						$sectionName = '';
					}
					$delimiter = strpos($dataLine, '=');
					if ($delimiter > 0) {
						$key = strtolower(trim(substr($dataLine, 0, $delimiter)));
						$value = trim(substr($dataLine, $delimiter +1));
						if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
							$value = substr($value, 1, -1);
						}						
						$iniSetting[$sectionName][$key] = stripcslashes($value);
					} else {
						$iniSetting[$sectionName][strtolower(trim($dataLine))] = '';
					}
				}
			}
		}
		return $iniSetting;
	}
		
} //End Class
?>
